import json
import random
import string
import time
import warnings

import requests
from loguru import logger

from utils.proxies_tools import get_company_ip_crawler_by_api

warnings.filterwarnings("ignore")
from apps.pdd.pdd.utils.pdd_verify import PddSliderVerify
from apps.pdd.pdd.utils.js import MSG_MAP


class Login(object):
    session = requests.Session()
    app_version = "7.68.0"
    channel = "oppo"
    phone_version = "R9"
    device_id = "eDX37CJK"
    session.headers = {
        "etag": device_id,
        "referer": "Android",
        "p-appname": "pinduoduo",
        "x-pdd-info": "bold_free%3Dfalse%26bold_product%3D%26front%3D0%26tz%3DAsia%2FShanghai",
        "x-pdd-queries": f"width=1080&height=1920&net=1&brand={channel}&model={phone_version}&osv=9&appv={app_version}&pl=2",
        "p-proc": "main",
        "p-mediainfo": "player=2.0.4&rtc=1.0.0",
        "user-agent": f"android Mozilla/5.0 (Linux; Android 9; {channel} {phone_version} Build/PQ3A.190605.04081832; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/91.0.4472.114 Mobile Safari/537.36  phh_android_version/{app_version} phh_android_build/a29b63f6c97be3675aff8f5f661fcddf1f6b713b phh_android_channel/{channel} pversion/0",
        "pdd-config": "V4:001.076800",
        "multi-set": "1,0,100000107",
    }
    logger.debug(session.headers)
    session.proxies = get_company_ip_crawler_by_api()
    print(session.proxies)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    def gen_anti_content(self, time, device_id=None):
        url = f"https://sekiro.wkaanig.cn/business/invoke?group=AntiToken&sekiro_token=c232bebc-68a8-4c3d-b310-e0d26876e58b&action=AntiTokenHandler&ts={time}"
        if device_id:
            url = url + f"&device_id={device_id}"
        resp = requests.get(url).json()
        print("gen_anti_content", resp)
        return resp["data"]

    def __init__(self, cookie=None):
        if cookie:
            self.session.cookies.update(cookie)
        else:
            self.session.get("https://api.pinduoduo.com/", verify=False)

    def send_sms_code(self, mobile="18888888888"):
        anti_token = self.gen_anti_content(time=int(time.time() * 1000))
        headers = {
            **self.session.headers,
            "content-type": "application/json;charset=UTF-8",
            "anti-token": anti_token,
        }
        url = "https://api.pinduoduo.com/api/sigerus/mobile/code/request"
        params = {"pdduid": ""}

        data = {
            "mobile": mobile,
            "app_version": self.app_version,
            "channel": "vivo",
            "platform": "2",
        }
        resp = self.session.post(url, headers=headers, params=params, json=data)
        result = resp.json()
        logger.debug(f"发送验证码结果: {mobile} {result} {self.session.cookies.get_dict()}")
        if result == {}:
            return_data = {
                "code": 200,
                "msg": "验证码发送成功",
                "error_code": None,
                "error_message": None,
                "verify_auth_token": None,
                "mobile": mobile,
            }
        else:
            return_data = {
                "code": 201,
                "msg": "验证码发送异常",
                "error_code": result.get("error_code"),
                "error_message": MSG_MAP.get(result.get("error_code"), 0),
                "verify_auth_token": result.get("verify_auth_token"),
                "mobile": mobile,
            }
        return return_data

    def verify_sms_code(self, mobile="18888888888", sms_code="123456"):
        """
        验证手机验证码
        {'_nano_fp': 'XpmaX5dyn5CJlpTqXo_Q5ij5GIQHsZYq4tFOzu3a', 'api_uid': 'CiTeiGYTi0WYaQBWC1sRAg==', 'PDDAccessToken': 'FWPIZ52ZHSSVDHVNJN2FD4O7YH72KLBROB2G6HOR2PJMV4BI5UXA1206a3a', 'acid': 'c2773fb181f75c74b9dda0e2db9dfeba'}
        正常：{'uid': 9847140310122, 'uin': 'ROGZA7R7XPMXA2IO5ES2IDNAUU_GEXDA', 'access_token': 'FWPIZ52ZHSSVDHVNJN2FD4O7YH72KLBROB2G6HOR2PJMV4BI5UXA1206a3a', 'acid': 'c2773fb181f75c74b9dda0e2db9dfeba', 'mobile_id': '7173939602209382400861', 'mobile_des': '189****1861', 'complete_newer': False}
        :param mobile:
        :param sms_code:
        :return:
        """
        anti_token = self.gen_anti_content(time=int(time.time() * 1000))
        headers = {
            **self.session.headers,
            "content-type": "application/json;charset=UTF-8",
            "anti-token": anti_token,
        }
        url = "https://api.pinduoduo.com/api/sigerus/login_mobile"
        data = {
            "mobile": mobile,
            "code": sms_code,
            "login_app_id": 5,
            "login_scene": "4",
            "refer_page_sn": "10002",
            "app_version": self.app_version,
            "channel": "vivo",
            "platform": "2",
        }
        resp = self.session.post(url, data=json.dumps(data, separators=(",", ":")), headers=headers)
        result = resp.json()
        logger.debug(f"校验验证码结果: {mobile} {sms_code} {result}")
        session_cookies = self.session.cookies.get_dict()
        logger.debug(f"session_cookies {session_cookies}")
        verify_success_cookies = {
            "api_uid": session_cookies.get("api_uid"),
            "acid": result.get("acid"),
            "PDDAccessToken": result.get("access_token"),
            "pdd_user_uin": result.get("uin"),
            "mobile_id": result.get("mobile_id"),
            "mobile_des": result.get("mobile_des"),
        }
        if result.get("uid"):
            verify_success_cookies.update({"pdd_user_id": str(result.get("uid"))})
        self.session.cookies.update(verify_success_cookies)
        if result.get("success") is False:
            return_data = {
                "code": 201,
                "msg": "验证码验证异常",
                "error_code": result.get("error_code"),
                "error_message": MSG_MAP.get(result.get("error_code"), 0),
                "mobile": mobile,
                "sms_code": sms_code,
                "cookies": None,
            }
        else:
            self.session.headers.update({"accesstoken": result.get("access_token")})
            self.session.cookies.update({"PDDAccessToken": result.get("access_token")})
            return_data = {
                "code": 200,
                "msg": "验证码验证成功",
                "error_code": None,
                "error_message": None,
                "mobile": mobile,
                "sms_code": sms_code,
                "cookies": verify_success_cookies,
                "headers": self.session.headers,
            }
        logger.info(return_data)
        return return_data

    def personal_check(self):
        session_cookie = self.session.cookies.get_dict()
        pdd_user_id = session_cookie.get("pdd_user_id")
        url = "https://api.pinduoduo.com/api/caterham/v3/query/personal"
        params = {
            "req_list_action_type": "0",
            "page_sn": "10001",
            "page_id": "personal.html",
            "list_id": f"{''.join(random.sample(string.ascii_lowercase + string.digits, 10))}",
            "offset": "0",
            "count": "20",
            "req_action_type": "0",
            "engine_version": "2.0",
            "pdduid": pdd_user_id,
        }
        print(params)
        anti_token = self.gen_anti_content(time=int(time.time() * 1000), device_id=self.device_id)
        headers = {
            **self.session.headers,
            "content-type": "application/json;charset=UTF-8",
            "anti-token": anti_token,
            "accesstoken": session_cookie.get("PDDAccessToken"),
        }
        response = self.session.get(url, params=params, headers=headers, verify=False)
        if response.status_code == 200:
            result = response.json()
            if result.get("success") is True:
                logger.success(f"个人主页请求成功 {pdd_user_id} status_code: {response.status_code}")
                return True
            else:
                logger.error(f"个人主页请求失败 {pdd_user_id} response: {result}")
                # if result.get("error_code") == 54001:
                #     cookie = PddSliderVerify(result.get("verify_auth_token")).run()
                return False
        else:
            logger.error(
                f"个人主页请求失败 {pdd_user_id} status_code: {response.status_code} response: {response.text}"
            )
            return False

    def run(self, mobile="18888888888"):
        send_result = self.send_sms_code(mobile)
        if send_result["code"] == 200:
            logger.success(f"发送验证码成功 {mobile}")
        else:
            logger.error(f"发送验证码失败 {mobile} {send_result}")
            verify_auth_token = send_result["verify_auth_token"]
            if verify_auth_token is None:
                raise Exception("发送验证码失败")
            cookie = PddSliderVerify(verify_auth_token).run()
            if cookie is False:
                raise Exception("滑块验证失败")
            # self.session.cookies.update(cookie)
        for _ in range(3):
            result = self.verify_sms_code(mobile, input("\n请输入短信验证码:"))
            if result.get("code") == 200:
                if self.personal_check():
                    return result
            elif result.get("error_code") == 40006:
                continue

    def refresh_token(self):
        session_cookie = self.session.cookies.get_dict()
        pdd_user_id = session_cookie.get("pdd_user_id")
        url = "https://api.pinduoduo.com/api/galilei/refresh/token"
        params = {"pdduid": pdd_user_id}
        data = {"scene": "daily"}
        anti_token = self.gen_anti_content(time=int(time.time() * 1000), device_id=self.device_id)
        headers = {
            **self.session.headers,
            "content-type": "application/json;charset=UTF-8",
            "anti-token": anti_token,
            "accesstoken": session_cookie.get("PDDAccessToken"),
        }
        resp = self.session.post(url, params=params, data=json.dumps(data, separators=(",", ":")), headers=headers)
        result = resp.json()
        # """
        # {
        # 	"server_time": 1714119766,
        # 	"access_token": "TTN6FGZDPX7O6HRXDSADHYUJYJ2LITV5H6PI6XOLI3QMNQUU5NEQ120725f",
        # 	"uid": 7440452829298,
        # 	"uin": "UMDXYBHGGD5CCUA4JAEC46JTHE_GEXDA"
        # }
        # """
        print(result)


if __name__ == "__main__":
    ck = {
        # 'api_uid': 'CiDWpGYt/JCZsABnAywcAg==',
        # 'acid': '5ff80388aada53337e701f902bac7ebf',
        # 'PDDAccessToken': '5YYW3KB73FISNKSK5R7TCAV5YOXUAF3CZ3COJKKSUM7K5MU2QHNQ123c879',
        # 'pdd_user_id': '5755281291208',
        # 'pdd_user_uin': 'HZVOFAFMIRQKBFXSN64OYO5ZGI_GEXDA',
        # 'api_uid': 'CiFp9mYuAIcAoABeA0ZsAg==',
        # 'acid': '1a0d8f78dba208afc41c44b1b66159b5',
        # 'PDDAccessToken': '2TS6S4CCXEWEPUFOOLV5YOXK2DI4CAA7WOYAQ4W56LOYTL7O2STQ1205479',
        # 'pdd_user_id': '2466085755988',
        # 'pdd_user_uin': 'GXJTZOUCPDYV55PPKYN3OZTUGA_GEXDA',
        # 'mobile_id': '7256676885099520000738',
        # 'mobile_des': '167****0738'
        # 'api_uid': 'CksoHGYvXXO0QwBhCN4oAg==',
        # 'acid': '8c9a863d8ee469fc7d6d78cdb4fa3bf6',
        # 'PDDAccessToken': 'ZN2MDTBNYZHRM7CLOJOIDR3VUBLETOG4I3NZTHEWBMFQTHQUYNNQ121c274',
        # 'pdd_user_uin': 'YD7VU6OJE2DG3NSYML6ZPXB5DE_GEXDA',
        # 'mobile_id': '230470325955518464638',
        # 'mobile_des': '156****3638',
        # 'pdd_user_id': '1576526274'
        # 'api_uid': 'CiVws2YvlUJtxwBtClO9Ag==',
        # 'acid': 'dc486f8b59419a2059b5c8e358659477',
        # 'PDDAccessToken': 'FMHWBAIGVN73FSJOS56WEKLEG5U5IK6DXB3IIPFAA6VR6KFF2Z5A121ed23',
        # 'pdd_user_uin': 'QGHVOCINWX4HY5OVUVR5C64XEQ_GEXDA',
        # 'mobile_id': '4716698570907484160223',
        # 'mobile_des': '155****5223',
        # 'pdd_user_id': '9715481226733'
    }
    with Login(ck) as self:
        mobie = "18888888888"
        # mobie = input("请输入手机号:")
        res = self.run(mobie)
        print("登录结果", res)

    # ck = {
    #     'api_uid': 'CiFp9mYuAIcAoABeA0ZsAg==',
    #     'acid': '1a0d8f78dba208afc41c44b1b66159b5',
    #     'PDDAccessToken': '2TS6S4CCXEWEPUFOOLV5YOXK2DI4CAA7WOYAQ4W56LOYTL7O2STQ1205479',
    #     'pdd_user_id': '2466085755988',
    #     'pdd_user_uin': 'GXJTZOUCPDYV55PPKYN3OZTUGA_GEXDA',
    #     'mobile_id': '7256676885099520000738',
    #     'mobile_des': '167****0738'
    # }
